package com.asia.algorithmcode.binaryTree;

import java.util.HashMap;
import java.util.Map;

/**
 * @DESCRIPTION: 105、从后序遍历和中序遍历恢复二叉树
 * @USER: wanfu
 * @DATE: 2025/5/9 星期五 15:53
 */
public class BuildTree2 {

    public static void main(String[] args) {
        int[] inorder = {9, 3, 15, 20, 7};
        int[] postorder = {9, 15, 7, 20, 3};

        TreeNode treeNode = new BuildTree2().buildTree(inorder, postorder);

        System.out.println(treeNode);
    }

    Map<Integer, Integer> map = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    private TreeNode build(int[] inorder, int il, int ir, int[] postorder, int pl, int pr) {
        if (il > ir) {
            return null;
        }

        TreeNode root = new TreeNode(postorder[pr]);
        Integer i = map.get(postorder[pr]);

        root.left = build(inorder, il, i - 1, postorder, pl, pl + i - 1 - il);
        root.right = build(inorder, i + 1, ir, postorder, pl + i - 1 - il + 1, pr-1);

        return root;
    }
}
